package com.example.demo.view;

import android.view.View;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

/**
 * @author: xtxiaolu
 * @date: 2023/7/7
 * 描述:
 */
public class CustomAdapter<T> extends BaseQuickAdapter<T, BaseViewHolder> {
    private int selectedPosition = -1;
    private OnItemClickListener itemClickListener;

    public CustomAdapter(@LayoutRes int layoutResId, @Nullable List<T> data) {
        super(layoutResId, data);
    }

    public void setSelectedPosition(int position) {
        this.selectedPosition = position;
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.itemClickListener = listener;
    }

    @Override
    protected void convert(BaseViewHolder holder, T item) {
        if (itemClickListener != null) {
            itemClickListener.convertView(holder, item, selectedPosition == holder.getBindingAdapterPosition());
        }
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemClickListener != null) {
                    itemClickListener.onItemClick(holder.getBindingAdapterPosition());
                }
            }
        });
    }

    public interface OnItemClickListener {
        void onItemClick(int position);

        void convertView(BaseViewHolder holder, Object item, boolean isSelected);
    }
}
